/*
 * Copyright (c) 2021-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package util;

import ohos.app.Context;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Map;

public class FileUtils {
    private static final String TAG= FileUtils.class.getSimpleName();

    private static final int BUFFER_LENGTH = 1024;
    public static final int DEFAULT_ERROR = -1;
    private static final String RAW_FILE_PATH = "entry/resources/rawfile/";

    /**
     * Copies a raw resource file, given its ID to the given location
     * @param context context
     * @param assetFileName resource id
     * @param outfile destination file
     * @param mode file permissions (E.g.: "755")
     * @throws IOException on error
     * @throws InterruptedException when interrupted
     * @return returns whether copy successful or not
     */
    public static boolean copyRawFile(Context context, String assetFileName, File outfile, String mode) throws IOException {
        String assetpath = RAW_FILE_PATH + assetFileName;
        final String abspath = outfile.getCanonicalPath();
        // Write the iptables binary
		try {
            OutputStream outputStream = new FileOutputStream(outfile);
            InputStream inputStream = context.getResourceManager().getRawFileEntry(assetpath).openRawFile();
            byte[] buf = new byte[BUFFER_LENGTH];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                // Do nothing
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                // Do nothing
            }
            Runtime.getRuntime().exec("chmod "+mode+" "+abspath).waitFor();
            return true;
        } catch (IOException | InterruptedException e) {
            Log.e(TAG, "Error Message " + e.getLocalizedMessage());
        }
        return false;
	}
}